package com.gxb.codebook;

import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import android.graphics.Bitmap;
import android.net.Uri;
import android.graphics.BitmapFactory;
import androidx.activity.EdgeToEdge;

import io.alterac.blurkit.BlurKit;
import io.alterac.blurkit.BlurLayout;

public class LoginActivity extends AppCompatActivity {
    private EditText Username;
    private EditText Password;
    private Button login_btn;
    private CheckBox rememberPass;
    private ImageView reg_image;
    private static final int PICK_IMAGE_REQUEST = 1;
    private boolean isBusyboxDownloaded = false;
    private boolean isScriptDownloaded = false;
    private BlurLayout blurLayout;
    private LinearLayout save_password_linearLayout;
    private BroadcastReceiver themeChangeReceiver;
    private LocalBroadcastManager localBroadcastManager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EdgeToEdge.enable(this);
        BlurKit.init(this);
        setContentView(R.layout.activity_login);

        // 初始化LocalBroadcastManager
        localBroadcastManager = LocalBroadcastManager.getInstance(this);

        // 初始化广播接收器
        initBroadcastReceiver();

        blurLayout = findViewById(R.id.blurLayout);
        Username = findViewById(R.id.username);
        Password = findViewById(R.id.password);
        login_btn = findViewById(R.id.login_btn);
        rememberPass = findViewById(R.id.save_password);
        reg_image = findViewById(R.id.reg_image);
        save_password_linearLayout = findViewById(R.id.save_password_linearLayout);

        loadSavedImage();
        loadCredentials();
        Fingerprint();

        reg_image.setOnClickListener(v -> openImagePicker());
        reg_image.setClipToOutline(true);

        save_password_linearLayout.setOnClickListener(v ->
                rememberPass.setChecked(!rememberPass.isChecked())
        );

        login_btn.setOnClickListener(v -> {
            String username = Username.getText().toString();
            String password = Password.getText().toString();
            if (username.isEmpty() || password.isEmpty()) {
                Toast.makeText(LoginActivity.this, "请填写完整信息", Toast.LENGTH_SHORT).show();

                // 发送登录失败广播 - 信息不完整
                Intent failIntent = new Intent("LOGIN_FAILED");
                failIntent.putExtra("reason", "信息不完整");
                localBroadcastManager.sendBroadcast(failIntent);
            } else if (!username.matches("^[A-Za-z0-9@#$%^&*.]+$") ||
                    !password.matches("^[A-Za-z0-9@#$%^&*.]+$")) {
                Toast.makeText(LoginActivity.this, "用户名和密码仅支持A-Z,a-z,0-9,@、#、$、%、^、&、*、.",
                        Toast.LENGTH_SHORT).show();

                // 发送登录失败广播 - 格式错误
                Intent failIntent = new Intent("LOGIN_FAILED");
                failIntent.putExtra("reason", "格式错误");
                localBroadcastManager.sendBroadcast(failIntent);
            } else if (!new File(getFilesDir(), "user_info.txt").exists()) {
                Toast.makeText(LoginActivity.this, "您还没有注册！", Toast.LENGTH_SHORT).show();

                // 发送登录失败广播 - 未注册
                Intent failIntent = new Intent("LOGIN_FAILED");
                failIntent.putExtra("reason", "未注册");
                localBroadcastManager.sendBroadcast(failIntent);
            } else {
                String wserpasswd = password + "+" + username;
                String encryptedPassword = UserPasswdConfound.encrypt(wserpasswd);
                if (rememberPass.isChecked()) {
                    saveCredentials();
                } else {
                    clearCredentials();
                }

                // 发送登录尝试广播
                Intent attemptIntent = new Intent("LOGIN_ATTEMPT");
                attemptIntent.putExtra("username", username);
                localBroadcastManager.sendBroadcast(attemptIntent);

                new VerifyTask(LoginActivity.this).execute(encryptedPassword);
            }
        });
    }

    private void initBroadcastReceiver() {
        themeChangeReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                if ("THEME_CHANGED".equals(intent.getAction())) {
                    recreate();
                }
            }
        };

        IntentFilter filter = new IntentFilter("THEME_CHANGED");
        localBroadcastManager.registerReceiver(themeChangeReceiver, filter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (localBroadcastManager != null && themeChangeReceiver != null) {
            try {
                localBroadcastManager.unregisterReceiver(themeChangeReceiver);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
    }

    private void clearCredentials() {
        SharedPreferences sharedPreferences = getSharedPreferences("SavedCredentials", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.remove("username");
        editor.remove("password");
        editor.remove("remember");
        editor.apply();

        // 发送清除凭据广播
        Intent clearIntent = new Intent("CREDENTIALS_CLEARED");
        localBroadcastManager.sendBroadcast(clearIntent);
    }

    @Override
    protected void onStart() {
        super.onStart();
        blurLayout.startBlur();
        blurLayout.lockView();
    }

    @Override
    protected void onStop() {
        super.onStop();
        blurLayout.pauseBlur();
    }

    private void openImagePicker() {
        Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        startActivityForResult(intent, PICK_IMAGE_REQUEST);

        // 发送打开图片选择器广播
        Intent pickerIntent = new Intent("IMAGE_PICKER_OPENED");
        localBroadcastManager.sendBroadcast(pickerIntent);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            Uri selectedImageUri = data.getData();
            String filePath = saveImageToInternalStorage(selectedImageUri);
            if (filePath != null) {
                try {
                    Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), selectedImageUri);
                    reg_image.setImageBitmap(bitmap);
                    SharedPreferences sharedPreferences = getSharedPreferences("SavedImage", Context.MODE_PRIVATE);
                    SharedPreferences.Editor editor = sharedPreferences.edit();
                    editor.putString("image_path", filePath);
                    editor.apply();

                    // 发送图片保存成功广播
                    Intent saveIntent = new Intent("IMAGE_SAVED");
                    saveIntent.putExtra("path", filePath);
                    localBroadcastManager.sendBroadcast(saveIntent);
                } catch (IOException e) {
                    e.printStackTrace();
                    Toast.makeText(this, "图片加载失败", Toast.LENGTH_SHORT).show();

                    // 发送图片加载失败广播
                    Intent failIntent = new Intent("IMAGE_LOAD_FAILED");
                    localBroadcastManager.sendBroadcast(failIntent);
                }
            }
        }
    }

    private String saveImageToInternalStorage(Uri imageUri) {
        String path = null;
        try {
            Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), imageUri);
            File file = new File(getFilesDir(), "selected_image.png");
            FileOutputStream out = new FileOutputStream(file);
            bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
            out.flush();
            out.close();
            path = file.getAbsolutePath();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return path;
    }

    private void saveCredentials() {
        String username = Username.getText().toString();
        String password = Password.getText().toString();
        SharedPreferences sharedPreferences = getSharedPreferences("SavedCredentials", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.putString("username", username);
        editor.putString("password", password);
        editor.putBoolean("remember", rememberPass.isChecked());
        editor.apply();

        // 发送保存凭据广播
        Intent saveIntent = new Intent("CREDENTIALS_SAVED");
        saveIntent.putExtra("username", username);
        saveIntent.putExtra("remember", rememberPass.isChecked());
        localBroadcastManager.sendBroadcast(saveIntent);
    }

    private void loadSavedImage() {
        SharedPreferences sharedPreferences = getSharedPreferences("SavedImage", Context.MODE_PRIVATE);
        String imagePath = sharedPreferences.getString("image_path", null);
        if (imagePath != null && new File(imagePath).exists()) {
            Bitmap bitmap = BitmapFactory.decodeFile(imagePath);
            reg_image.setImageBitmap(bitmap);

            // 发送图片加载成功广播
            Intent loadIntent = new Intent("IMAGE_LOADED");
            loadIntent.putExtra("path", imagePath);
            localBroadcastManager.sendBroadcast(loadIntent);
        }
    }

    private void Fingerprint() {
        File file = new File(getFilesDir(), "true");
        if (file.exists()) {
            FingerprintLogin fingerprintLogin = new FingerprintLogin(this, new FingerprintLogin.AuthenticationCallback() {
                @Override
                public void onAuthenticationResult(boolean success) {
                    if (success) {
                        Intent intent = new Intent(LoginActivity.this, HomeActivity.class);
                        intent.putExtra("username", Username.getText().toString());
                        startActivity(intent);
                        finish();

                        // 发送指纹验证成功广播
                        Intent successIntent = new Intent("FINGERPRINT_SUCCESS");
                        localBroadcastManager.sendBroadcast(successIntent);
                    } else {
                        // 发送指纹验证失败广播
                        Intent failIntent = new Intent("FINGERPRINT_FAILED");
                        localBroadcastManager.sendBroadcast(failIntent);
                    }
                }
            });
            fingerprintLogin.authenticate();

            // 发送指纹验证开始广播
            Intent startIntent = new Intent("FINGERPRINT_STARTED");
            localBroadcastManager.sendBroadcast(startIntent);
        }
    }

    private void loadCredentials() {
        SharedPreferences sharedPreferences = getSharedPreferences("SavedCredentials", Context.MODE_PRIVATE);
        String savedUsername = sharedPreferences.getString("username", "");
        String savedPassword = sharedPreferences.getString("password", "");
        boolean remember = sharedPreferences.getBoolean("remember", false);

        if (remember) {
            Username.setText(savedUsername);
            Password.setText(savedPassword);
            rememberPass.setChecked(true);

            // 发送凭据加载成功广播
            Intent loadIntent = new Intent("CREDENTIALS_LOADED");
            loadIntent.putExtra("username", savedUsername);
            localBroadcastManager.sendBroadcast(loadIntent);
        }
    }

    public void doClick(View view) {
        File file = new File(getFilesDir(), "user_info.txt");
        if (file.exists()) {
            Toast.makeText(this, "您已经注册过了！", Toast.LENGTH_SHORT).show();

            // 发送已注册广播
            Intent regIntent = new Intent("ALREADY_REGISTERED");
            localBroadcastManager.sendBroadcast(regIntent);
        } else {
            startActivity(new Intent(this, RegActivity.class));

            // 发送跳转到注册页面广播
            Intent regIntent = new Intent("NAVIGATE_TO_REGISTER");
            localBroadcastManager.sendBroadcast(regIntent);
        }
    }

    public void toForget(View view) {
        startActivity(new Intent(this, ForgetActivity.class));

        // 发送跳转到忘记密码页面广播
        Intent forgetIntent = new Intent("NAVIGATE_TO_FORGET");
        localBroadcastManager.sendBroadcast(forgetIntent);
    }

    private static class VerifyTask extends AsyncTask<String, Void, Boolean> {
        private WeakReference<LoginActivity> weakActivity;

        VerifyTask(LoginActivity activity) {
            this.weakActivity = new WeakReference<>(activity);
        }

        @Override
        protected Boolean doInBackground(String... params) {
            String encryptedPassword = params[0];
            LoginActivity activity = weakActivity.get();
            if (activity == null) {
                return false;
            }
            return activity.verifyUser(encryptedPassword);
        }

        @Override
        protected void onPostExecute(Boolean result) {
            LoginActivity activity = weakActivity.get();
            if (activity == null || activity.isFinishing()) {
                return;
            }

            if (result) {
                Intent intent = new Intent(activity, HomeActivity.class);
                intent.putExtra("username", activity.Username.getText().toString());
                intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                activity.startActivity(intent);
                activity.finish();

                // 发送登录成功广播
                Intent successIntent = new Intent("LOGIN_SUCCESS");
                successIntent.putExtra("username", activity.Username.getText().toString());
                activity.localBroadcastManager.sendBroadcast(successIntent);
            } else {
                Toast.makeText(activity, "登录失败，账户或密码错误！", Toast.LENGTH_LONG).show();

                // 发送登录失败广播 - 凭据错误
                Intent failIntent = new Intent("LOGIN_FAILED");
                failIntent.putExtra("reason", "凭据错误");
                activity.localBroadcastManager.sendBroadcast(failIntent);
            }
        }
    }

    private boolean verifyUser(String encryptedPassword) {
        File file = new File(getFilesDir(), "user_info.txt");
        if (!file.exists()) {
            return false;
        }

        try (BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)))) {
            String line;
            while ((line = reader.readLine()) != null) {
                if (line.contains(encryptedPassword)) {
                    return true;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
